//
//  HXAddMettingNotifyViewController.m
//  KD
//
//  Created by ifly on 16/7/14.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXAddMettingNotifyViewController.h"
#import "UIButton+WebCache.h"
#import "HXCompanyNotifyTableViewController.h"

#import "NSString+Frame.h"
#import "HXUpDataImageModel.h"

@interface HXAddMettingNotifyViewController ()<UITextViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (strong, nonatomic) UIScrollView *backScrollView;
@property (nonatomic,strong) UILabel *titleLabel;
@property (strong, nonatomic) UITextView *titleTextView;
@property (nonatomic,strong) UILabel *timeTitleLabel;
@property (strong, nonatomic) UILabel *timeLabel;
@property (strong, nonatomic) UITextView *contentTextView;
@property (strong, nonatomic) UIButton *sendBtn;
@property (strong, nonatomic) UILabel *titlePlaceholdLabel;
@property (strong, nonatomic) UILabel *contentPlaceholdLabel;
@property (nonatomic,strong) UIScrollView *photoScrollView;
@property (nonatomic,strong) UILongPressGestureRecognizer *longPress;
@property (nonatomic,strong) NSMutableArray *phothMuArray;
@property (nonatomic,strong) NSMutableArray *photoFilePathArr;
@property (nonatomic,strong) UIButton *photoBtn;
@property(nonatomic,strong) HXUpDataImageModel *dict;
@property (nonatomic,strong) UIView * lineOne;
@property (nonatomic,strong) UIView * lineTwo;
@end

@implementation HXAddMettingNotifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, HXSCREEN_WIDTH, HXSCREEN_HEIGHT)];
    
    /**
     标题
     */
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30 + 10, 44, 30)];
//    self.titleLabel.backgroundColor = [UIColor orangeColor];
    self.titleLabel.text = @"标题:";
    [self.backScrollView addSubview:self.titleLabel];
    self.titlePlaceholdLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.titleLabel.right + 10, self.titleLabel.y+2, HXSCREEN_WIDTH - (10+self.titleLabel.width+10) - 10 , 30)];
    self.titlePlaceholdLabel.text = @" 请输入标题";
    self.titlePlaceholdLabel.textColor = [UIColor lightGrayColor];
    [self.backScrollView addSubview:self.titlePlaceholdLabel];
    self.titleTextView = [[UITextView alloc] initWithFrame:CGRectMake(self.titleLabel.right + 10, self.titleLabel.y, HXSCREEN_WIDTH - (10+self.titleLabel.width+10) - 10 , 30)];
    self.titleTextView.font = [UIFont systemFontOfSize:18];
    self.titleTextView.backgroundColor = [UIColor clearColor];
    [self.backScrollView addSubview:self.titleTextView];
    _lineOne = [[UIView alloc] initWithFrame:CGRectMake(8, self.titleTextView.bottom + 10, HXSCREEN_WIDTH - 16, 1)];
    _lineOne.backgroundColor = [UIColor grayColor];
    [self.backScrollView addSubview:_lineOne];
    /**
     时间
     */
    self.timeTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lineOne.bottom + 20, 44, 30)];
    self.timeTitleLabel.text = @"时间:";
    [self.backScrollView addSubview:self.timeTitleLabel];
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.timeTitleLabel.right + 10, self.timeTitleLabel.y, 200, 30)];
//    self.timeLabel.backgroundColor = [UIColor redColor];
    [self.backScrollView addSubview:self.timeLabel];
    _lineTwo = [[UIView alloc] initWithFrame:CGRectMake(8, self.timeTitleLabel.bottom + 10, HXSCREEN_WIDTH - 16, 1)];
    _lineTwo.backgroundColor = [UIColor grayColor];
    [self.backScrollView addSubview:_lineTwo];
    /**
     内容
     */
    self.contentPlaceholdLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, _lineTwo.bottom + 20, HXSCREEN_WIDTH - 20, 30)];
    self.contentPlaceholdLabel.text = @"请输入内容";
    self.contentPlaceholdLabel.textColor = [UIColor lightGrayColor];
    [self.backScrollView addSubview:self.contentPlaceholdLabel];
    _contentTextView = [[UITextView alloc] init];
    self.contentTextView.frame = CGRectMake(10, self.contentPlaceholdLabel.top, HXSCREEN_WIDTH - 20, 150);
    self.contentTextView.font = [UIFont systemFontOfSize:18];
    self.contentTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.contentTextView.layer.borderWidth = 0.5f;
    self.contentTextView.backgroundColor = [UIColor clearColor];
    [self.backScrollView addSubview:self.contentTextView];
    self.titleTextView.delegate = self;
    self.contentTextView.delegate = self;
    /**
     提交
     */
    self.sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendBtn.frame = CGRectMake(20, self.contentTextView.bottom + 100 + 40 + 40, HXSCREEN_WIDTH - 40, 40);
    self.sendBtn.backgroundColor = [UIColor orangeColor];
    [self.sendBtn setTitle:@"提交" forState:UIControlStateNormal];
    [self.sendBtn addTarget:self action:@selector(sendBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.backScrollView addSubview:self.sendBtn];
    
    [self.view addSubview:self.backScrollView];
    
    self.backScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, self.sendBtn.y + self.sendBtn.height + 40);
    
    UIButton *backButton=[[UIButton alloc]init];
    // 设置返回图片
    [backButton setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    backButton.contentMode = UIViewContentModeLeft;
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    // [button sizeToFit];//让按钮大小跟随内容
    // 让按钮的内容往左边偏移10
    backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [backButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    backButton.frame=CGRectMake(0, 0,37,90);
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:backButton];
    
    
    [self addPhoto];
    [self getNetTime];
}

-(void)backButton {
    
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_DealWithJPUSH_IflyNotify" object:nil userInfo:nil];
}



/**
 发送通知
 */
-(void)sendBtnClick {
    
    if (self.titleTextView.text.length <= 0 || self.contentTextView.text.length <= 0) {
        
        [LTAlertView showTitle:@"⚠️"
                       message:@"请完善信息之后,再次提交通知!"
                  ButtonTitles:@[@"确定"]
                    OnTapBlock:^(LTAlertView *alert, NSInteger num) {
            
        }];
        return;
    }
    
    if (self.titleTextView.text.length>0 && self.contentTextView.text.length>0) {
        [SVProgressHUD showWithStatus:@"正在上传"];
        [NetworkAPI sendCompanyPersonalNotifyWithC_SendID:[UserDefaultHandler getUserDetault:kID]
                                               C_SendName:[UserDefaultHandler getUserDetault:kUsers_PersonName]
                                                C_OrgCode:[UserDefaultHandler getUserDetault:kUsers_Organization]
                                                  C_Title:self.titleTextView.text
                                                C_Content:self.contentTextView.text
                                                 C_IsSend:@"true"
                                                  picList:self.photoFilePathArr
                                                  Success:^(HXBaseModel *result) {
                                                      
                                                      if ([result.code isEqualToString:@"200"]) {
                                                          [SVProgressHUD showSuccessWithStatus:@"上传成功"];

                                                          [self backButton];
                                                          
                                                          
                                                      }
                                                      
                                                  } failure:^(NSError *err) {
                                                      [SVProgressHUD showErrorWithStatus:@"上传失败"];
                                                  }];
    }
    else {
        [LTAlertView showTitle:@"提示" message:@"未按照相应格式填写" ButtonTitles:@[@"确定"] OnTapBlock:^(LTAlertView *alert, NSInteger num) {
            
        }];
    }
    
    
}

/**
 获取网络时间
 */
-(void)getNetTime {
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code isEqualToString:@"200"]) {
            self.timeLabel.text =  [NSString stringWithFormat:@"%@",result.ServerDate];
            self.timeLabel.textAlignment = NSTextAlignmentLeft;
        }
    } failure:^(NSError *err) {
        [SVProgressHUD showErrorWithStatus:@"获取网络时间失败,请检查网络"];
    }];
}

/**
 添加照片
 */
-(void)addPhoto {
    _photoScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.contentTextView.bottom + 40, HXSCREEN_WIDTH, 100)];
//    _photoScrollView.backgroundColor = [UIColor grayColor];
    [self.backScrollView addSubview:_photoScrollView];
    UIButton * addPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addPhotoBtn.tag = 100;
    addPhotoBtn.frame = CGRectMake(10, 0, 100, 100);
    //addPhotoBtn.backgroundColor = [UIColor redColor];
    [addPhotoBtn setImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
    [addPhotoBtn addTarget:self action:@selector(addPhotoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_photoScrollView addSubview:addPhotoBtn];
    //长按手势
    _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pictureLongPress:)];
    [_photoScrollView addGestureRecognizer:_longPress];
}


/**
 拍照选取照片
 */

-(void)addPhotoBtnClick {
    
    [self.contentTextView resignFirstResponder];
    
    CTActionSheet *actionSheet = [CTActionSheet actionSheetWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相机相册选择" HandleBlock:^(int btnIndex) {
        if (btnIndex == 0) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
                picker.delegate = self;
                picker.allowsEditing = YES;//设置可编辑
                picker.sourceType = sourceType;
                [self presentViewController:picker animated:YES completion:^{
                }];//进入照相界面
            }
        }else if (btnIndex == 1){
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            }
            pickerImage.delegate = self;
            pickerImage.allowsEditing = YES;
            [self presentViewController:pickerImage animated:YES completion:^{
            }];
        }else{
        }
    }];
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    if ([window.subviews containsObject:self.view]) {
        [actionSheet showInView:self.view];
    } else {
        [actionSheet showInView:window];
    }
    
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
    if(!originalImage){
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    [self sendUpImage:originalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/**
 上传照片
 */
-(void)sendUpImage:(UIImage *)image {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    if  (imageData.length>300000){
        UIImage *image = [UIImage imageWithData:imageData];
        imageData = UIImageJPEGRepresentation(image, 0.005);
    }
    [self.phothMuArray addObject:image];

    [self setPhotoInScrollView];
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"application/json", @"text/json",@"text/html", @"text/javascript", @"text/plain"]];
    [manager POST:[NSString stringWithFormat:@"%@/DayWork/SendFiles.ashx",API_HOST] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"name" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        _dict = [[HXUpDataImageModel alloc]initWithDictionary:responseObject error:nil];
        if ([_dict.code isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"图片上传成功"];
            //图片网址_dict.FilePath
            NSDictionary * photoPath = @{
                                         @"Files_Path":_dict.FilePath
                                         };
                [self.photoFilePathArr addObject:photoPath];
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"图上传失败"];
    }];
}


/**
 设置scrollView
 */
-(void)setPhotoInScrollView {
    for (int i = 0; i<self.phothMuArray.count; i++) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.tag = 1001 + i;
        _photoBtn.frame = CGRectMake(10 + 110 * (i + 1), 0, 100, 100);
        [_photoBtn setImage:self.phothMuArray[i] forState:UIControlStateNormal];
        [_photoBtn addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_photoScrollView addSubview:_photoBtn];
    }
    _photoScrollView.contentSize = CGSizeMake(110 * (self.phothMuArray.count + 1), 100);
}
-(void)photoBtnClick:(UIButton *)btn {
    
    NSLog(@"btn.tag-----------%ld",btn.tag);
}

/**
 修改scrollView
 */
-(void)getPhotoInScrollView {
    
    for (int i = 0; i<self.photoFilePathArr.count; i++) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.tag = 1001 + i;
        _photoBtn.frame = CGRectMake(10 + 110 * (i + 1), 0, 100, 100);
        [_photoBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.photoFilePathArr[i]] forState:UIControlStateNormal];
        [_photoBtn addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_photoScrollView addSubview:_photoBtn];
    }
    _photoScrollView.contentSize = CGSizeMake(110 * (self.photoFilePathArr.count + 1), 100);
}


-(void)pictureLongPress:(UILongPressGestureRecognizer *)longPress {
    
    NSMutableArray * arrayLast = [[NSMutableArray alloc] init];
    CGPoint point = [longPress locationInView:self.photoScrollView];
    NSString * strPoint =NSStringFromCGPoint(point);
    NSArray * array = [strPoint componentsSeparatedByString:@","];
    NSArray * arrayTwo = [array[0] componentsSeparatedByString:@"{"];
    for (int i = 0; i <= 20; i++) {
        if ([arrayTwo[1] intValue] > (110*i+10)) {
            [arrayLast addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    NSString * removeIndexStr = [NSString stringWithFormat:@"%@",[arrayLast lastObject]];
    
        
        if ([removeIndexStr integerValue] > self.phothMuArray.count) {
            NSLog(@"揍你");
        }
        else {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否删除照片"
                                                                                      message:@""
                                                                               preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction * cancelButton = [UIAlertAction actionWithTitle:@"取消"
                                                                    style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction *action) {
                                                                      NSLog(@"取消");
                                                                  }];
            UIAlertAction * creationBtn = [UIAlertAction actionWithTitle:@"删除"
                                                                   style:UIAlertActionStyleDestructive
                                                                 handler:^(UIAlertAction * _Nonnull action) {
                                                                     [_photoScrollView removeFromSuperview];
                                                                     _photoScrollView = nil;
                                                                     [self.photoFilePathArr removeObjectAtIndex:[removeIndexStr integerValue] - 1];
                                                                     [self.phothMuArray removeObjectAtIndex:[removeIndexStr integerValue] - 1];
                                                                     if (_photoBtn.tag == 1000 + [removeIndexStr integerValue]) {
                                                                         [_photoBtn removeFromSuperview];
                                                                     }
                                                                     [self addPhoto];
                                                                     [self setPhotoInScrollView];
                                                                 }];
            [alertController addAction:cancelButton];
            [alertController addAction:creationBtn];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
        }
}




-(void)textViewDidChange:(UITextView *)textView {
    
    if (self.contentTextView.text.length > 0) {
        self.contentPlaceholdLabel.text = @"";
    }
    if (self.contentTextView.text.length == 0) {
        self.contentPlaceholdLabel.text = @"请输入内容";
    }
    if (self.titleTextView.text.length > 0) {
        self.titlePlaceholdLabel.text = @"";
    }
    if (self.titleTextView.text.length == 0) {
        self.titlePlaceholdLabel.text = @"请输入标题";
    }
    
    CGFloat titleViewHight = [self.titleTextView.text heightWithFont:[UIFont systemFontOfSize:18] withinWidth:HXSCREEN_WIDTH -(21+45+8+20)-8];
    CGRect oldFrame = self.titleTextView.frame;
    oldFrame.size.height = titleViewHight;
    self.titleTextView.frame = oldFrame;
    
    _lineOne.frame = CGRectMake(8, self.titleTextView.bottom + 10, HXSCREEN_WIDTH - 16, 1);
    self.timeTitleLabel.frame = CGRectMake(10, _lineOne.bottom + 20, 44, 30);
    self.timeLabel.frame = CGRectMake(self.timeTitleLabel.right + 10, self.timeTitleLabel.y, 200, 30);
    _lineTwo.frame = CGRectMake(8, self.timeTitleLabel.bottom + 10, HXSCREEN_WIDTH - 16, 1);
    self.contentPlaceholdLabel.frame = CGRectMake(10, _lineTwo.bottom + 20 + 5, HXSCREEN_WIDTH - 20, 30);
    self.contentTextView.frame = CGRectMake(10, self.contentPlaceholdLabel.top, HXSCREEN_WIDTH - 20, 150);
    
    CGFloat contentViewHight = [self.contentTextView.text heightWithFont:[UIFont systemFontOfSize:18] withinWidth:HXSCREEN_WIDTH - 40];
    if (contentViewHight > 150) {
        CGRect contentOldFrame = self.contentTextView.frame;
        contentOldFrame.size.height = contentViewHight;
        self.contentTextView.frame = contentOldFrame;
    }
    _photoScrollView.frame = CGRectMake(0, self.contentTextView.bottom + 40, HXSCREEN_WIDTH,100);
    self.sendBtn.frame = CGRectMake(20, self.contentTextView.bottom + 100 + 40 + 40, HXSCREEN_WIDTH - 40, 40);
    
    if (contentViewHight <= 150) {
        self.backScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, HXSCREEN_HEIGHT + titleViewHight);
        //NSLog(@"-----------------%lf",self.backScrollView.contentSize.height);
    }
    if (contentViewHight > 150) {
        self.backScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, HXSCREEN_HEIGHT + titleViewHight + contentViewHight - 150);
        //NSLog(@"-----------------%lf",self.backScrollView.contentSize.height);

    }
}

-(NSMutableArray *)phothMuArray {
    if (_phothMuArray == nil) {
        _phothMuArray = [[NSMutableArray alloc] init];
    }
    return _phothMuArray;
}
-(NSMutableArray *)photoFilePathArr {
    if (_photoFilePathArr == nil) {
        _photoFilePathArr = [[NSMutableArray alloc] init];
    }
    return _photoFilePathArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
